import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { StockDataService, StockAlertRule } from '../../shared/services/stock-data.service';
import { Subscription } from 'rxjs';

// 添加Bootstrap声明
declare var bootstrap: any;

@Component({
  selector: 'app-alert-rules',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, RouterModule],
  template: `
    <div class="container-fluid">
      <div class="row mt-3">
        <div class="col-12">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h2>库存预警规则管理</h2>
            <div>
              <button class="btn btn-primary" (click)="showAddRuleModal()">
                <i class="bi bi-plus-circle"></i> 添加规则
              </button>
            </div>
          </div>
          
          <!-- 默认阈值设置 -->
          <div class="card mb-4">
            <div class="card-header bg-light">
              <h5>全局默认设置</h5>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-6">
                  <div class="mb-3">
                    <label for="defaultThreshold" class="form-label">默认低库存预警阈值</label>
                    <div class="input-group">
                      <input type="number" class="form-control" id="defaultThreshold" 
                             [(ngModel)]="defaultThreshold" min="0" step="1">
                      <button class="btn btn-outline-secondary" type="button" (click)="saveDefaultThreshold()">
                        保存
                      </button>
                    </div>
                    <small class="text-muted">当商品库存低于此阈值时将触发预警，除非有特定规则覆盖。</small>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="alert alert-info">
                    <p><strong>预警规则说明：</strong></p>
                    <ul>
                      <li>系统会按优先级从高到低匹配适用的规则</li>
                      <li>若无匹配规则，则使用默认阈值</li>
                      <li>规则可以针对特定货品、类型或仓库设置</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 规则列表 -->
          <div class="card">
            <div class="card-header bg-light">
              <div class="d-flex justify-content-between">
                <h5>预警规则列表</h5>
                <div>
                  <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="showInactiveRules"
                           [(ngModel)]="showInactiveRules">
                    <label class="form-check-label" for="showInactiveRules">
                      显示未启用规则
                    </label>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-striped">
                  <thead>
                    <tr>
                      <th>启用状态</th>
                      <th>规则名称</th>
                      <th>适用范围</th>
                      <th>预警阈值</th>
                      <th>优先级</th>
                      <th>最后更新</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr *ngFor="let rule of filteredRules">
                      <td>
                        <div class="form-check form-switch">
                          <input class="form-check-input" type="checkbox"
                                 [id]="'ruleStatus_' + rule.id"
                                 [checked]="rule.isActive"
                                 (change)="toggleRuleStatus(rule)">
                        </div>
                      </td>
                      <td>
                        <span *ngIf="rule.isGlobal" class="badge bg-primary me-1">全局</span>
                        {{getRuleName(rule)}}
                      </td>
                      <td>
                        <ng-container *ngIf="!rule.isGlobal">
                          <span *ngIf="rule.goodsCode" class="badge bg-secondary me-1">商品: {{rule.goodsCode}}</span>
                          <span *ngIf="rule.goodsType" class="badge bg-info me-1">类型: {{rule.goodsType}}</span>
                          <span *ngIf="rule.warehouseName" class="badge bg-warning me-1">仓库: {{rule.warehouseName}}</span>
                        </ng-container>
                        <span *ngIf="rule.isGlobal">适用于所有库存</span>
                      </td>
                      <td>{{rule.thresholdValue}}</td>
                      <td>
                        <span [ngClass]="getPriorityBadgeClass(rule.priority)">
                          {{getPriorityText(rule.priority)}}
                        </span>
                      </td>
                      <td>{{rule.updatedAt | date:'yyyy-MM-dd HH:mm'}}</td>
                      <td>
                        <button class="btn btn-sm btn-outline-primary me-1" (click)="editRule(rule)">
                          <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" (click)="deleteRule(rule)">
                          <i class="bi bi-trash"></i>
                        </button>
                      </td>
                    </tr>
                    <tr *ngIf="filteredRules.length === 0">
                      <td colspan="7" class="text-center py-3">
                        暂无预警规则数据，请点击"添加规则"按钮创建新规则。
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑规则模态框 -->
    <div class="modal fade" id="ruleModal" tabindex="-1" aria-labelledby="ruleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="ruleModalLabel">{{isEditing ? '编辑预警规则' : '添加预警规则'}}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
          </div>
          <div class="modal-body">
            <form [formGroup]="ruleForm">
              <div class="mb-3">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" id="isGlobalRule"
                         formControlName="isGlobal" (change)="onGlobalChange()">
                  <label class="form-check-label" for="isGlobalRule">
                    全局规则（适用于所有库存）
                  </label>
                </div>
              </div>
              
              <div *ngIf="!ruleForm.value.isGlobal" class="mb-3">
                <label class="form-label">适用范围</label>
                <div class="row g-2">
                  <div class="col-md-12">
                    <input type="text" class="form-control" placeholder="商品编码（可选）"
                           formControlName="goodsCode">
                  </div>
                  <div class="col-md-6">
                    <input type="text" class="form-control" placeholder="货品类型（可选）"
                           formControlName="goodsType">
                  </div>
                  <div class="col-md-6">
                    <input type="text" class="form-control" placeholder="仓库名称（可选）"
                           formControlName="warehouseName">
                  </div>
                </div>
                <div *ngIf="shouldShowScopeError()" class="text-danger mt-1 small">
                  请至少指定商品编码、货品类型或仓库名称中的一项
                </div>
              </div>
              
              <div class="mb-3">
                <label for="thresholdValue" class="form-label">预警阈值</label>
                <input type="number" class="form-control" id="thresholdValue"
                       formControlName="thresholdValue" min="0" step="1">
                <div *ngIf="ruleForm.get('thresholdValue')?.invalid && 
                           ruleForm.get('thresholdValue')?.touched" 
                     class="text-danger small">
                  预警阈值必须是大于或等于0的整数
                </div>
              </div>
              
              <div class="mb-3">
                <label for="priority" class="form-label">优先级</label>
                <select class="form-select" id="priority" formControlName="priority">
                  <option value="1">最高</option>
                  <option value="2">高</option>
                  <option value="3">中</option>
                  <option value="4">低</option>
                  <option value="5">最低</option>
                </select>
              </div>
              
              <div class="mb-3">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" id="isActiveRule"
                         formControlName="isActive">
                  <label class="form-check-label" for="isActiveRule">
                    启用规则
                  </label>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" (click)="saveRule()" 
                    [disabled]="ruleForm.invalid || !isValidScope()">
              保存
            </button>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .badge {
      font-size: 0.9em;
    }
  `]
})
export class AlertRulesComponent implements OnInit, OnDestroy {
  // 预警规则列表
  alertRules: StockAlertRule[] = [];
  filteredRules: StockAlertRule[] = [];
  
  // 默认阈值
  defaultThreshold = 10;
  
  // UI状态
  showInactiveRules = true;
  isEditing = false;
  currentRuleId: string | null = null;
  
  // 表单
  ruleForm: FormGroup;
  
  // 模态框实例
  private ruleModal: any;
  
  // 数据订阅
  private subscription = new Subscription();

  constructor(
    private stockDataService: StockDataService,
    private fb: FormBuilder
  ) {
    this.ruleForm = this.createRuleForm();
  }

  ngOnInit(): void {
    // 获取默认阈值
    this.defaultThreshold = this.stockDataService.getDefaultLowStockThreshold();
    
    // 获取预警规则列表
    this.subscription.add(
      this.stockDataService.alertRules$.subscribe(rules => {
        this.alertRules = rules;
        this.filterRules();
      })
    );
    
    // 初始化模态框
    document.addEventListener('DOMContentLoaded', () => {
      this.ruleModal = new bootstrap.Modal(document.getElementById('ruleModal'));
    });
  }
  
  /**
   * 创建规则表单
   */
  private createRuleForm(): FormGroup {
    return this.fb.group({
      isGlobal: [false],
      goodsCode: [''],
      goodsType: [''],
      warehouseName: [''],
      thresholdValue: [10, [Validators.required, Validators.min(0), Validators.pattern("^[0-9]*$")]],
      priority: [3, Validators.required],
      isActive: [true]
    });
  }
  
  /**
   * 根据启用状态筛选规则
   */
  filterRules(): void {
    this.filteredRules = this.showInactiveRules 
      ? [...this.alertRules]
      : this.alertRules.filter(rule => rule.isActive);
    
    // 按优先级排序
    this.filteredRules.sort((a, b) => a.priority - b.priority);
  }
  
  /**
   * 保存默认预警阈值
   */
  saveDefaultThreshold(): void {
    this.stockDataService.setDefaultLowStockThreshold(this.defaultThreshold);
    alert('默认阈值已更新');
  }
  
  /**
   * 切换规则启用状态
   */
  toggleRuleStatus(rule: StockAlertRule): void {
    const updatedRule: StockAlertRule = {
      ...rule,
      isActive: !rule.isActive
    };
    
    this.stockDataService.saveAlertRule(updatedRule);
  }
  
  /**
   * 显示添加规则模态框
   */
  showAddRuleModal(): void {
    this.isEditing = false;
    this.currentRuleId = null;
    this.ruleForm.reset({
      isGlobal: false,
      goodsCode: '',
      goodsType: '',
      warehouseName: '',
      thresholdValue: 10,
      priority: 3,
      isActive: true
    });
    
    this.ruleModal.show();
  }
  
  /**
   * 编辑规则
   */
  editRule(rule: StockAlertRule): void {
    this.isEditing = true;
    this.currentRuleId = rule.id;
    
    this.ruleForm.patchValue({
      isGlobal: rule.isGlobal,
      goodsCode: rule.goodsCode || '',
      goodsType: rule.goodsType || '',
      warehouseName: rule.warehouseName || '',
      thresholdValue: rule.thresholdValue,
      priority: rule.priority,
      isActive: rule.isActive
    });
    
    this.ruleModal.show();
  }
  
  /**
   * 保存规则
   */
  saveRule(): void {
    if (this.ruleForm.invalid || !this.isValidScope()) {
      return;
    }
    
    const formValue = this.ruleForm.value;
    const rule: StockAlertRule = {
      id: this.currentRuleId || '',
      isGlobal: formValue.isGlobal,
      goodsCode: formValue.isGlobal ? undefined : formValue.goodsCode || undefined,
      goodsType: formValue.isGlobal ? undefined : formValue.goodsType || undefined,
      warehouseName: formValue.isGlobal ? undefined : formValue.warehouseName || undefined,
      thresholdValue: formValue.thresholdValue,
      priority: formValue.priority,
      isActive: formValue.isActive,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    this.stockDataService.saveAlertRule(rule);
    this.ruleModal.hide();
  }
  
  /**
   * 删除规则
   */
  deleteRule(rule: StockAlertRule): void {
    if (confirm(`确定要删除规则"${this.getRuleName(rule)}"吗？`)) {
      this.stockDataService.deleteAlertRule(rule.id);
    }
  }
  
  /**
   * 获取规则名称
   */
  getRuleName(rule: StockAlertRule): string {
    if (rule.isGlobal) {
      return '全局默认规则';
    }
    
    const parts = [];
    
    if (rule.goodsCode) {
      parts.push(`商品${rule.goodsCode}`);
    }
    
    if (rule.goodsType) {
      parts.push(`${rule.goodsType}类型`);
    }
    
    if (rule.warehouseName) {
      parts.push(`${rule.warehouseName}仓库`);
    }
    
    return parts.join('-') + '预警规则';
  }
  
  /**
   * 获取优先级文本
   */
  getPriorityText(priority: number): string {
    switch (priority) {
      case 1: return '最高';
      case 2: return '高';
      case 3: return '中';
      case 4: return '低';
      case 5: return '最低';
      default: return '未知';
    }
  }
  
  /**
   * 获取优先级徽章样式
   */
  getPriorityBadgeClass(priority: number): string {
    switch (priority) {
      case 1: return 'badge bg-danger';
      case 2: return 'badge bg-warning';
      case 3: return 'badge bg-info';
      case 4: return 'badge bg-success';
      case 5: return 'badge bg-secondary';
      default: return 'badge bg-light';
    }
  }
  
  /**
   * 检查规则范围是否有效
   */
  isValidScope(): boolean {
    const formValue = this.ruleForm.value;
    
    if (formValue.isGlobal) {
      return true;
    }
    
    // 非全局规则，至少需要指定商品编码、货品类型或仓库名称中的一项
    return !!(formValue.goodsCode || formValue.goodsType || formValue.warehouseName);
  }
  
  /**
   * 判断是否显示范围错误
   */
  shouldShowScopeError(): boolean {
    const form = this.ruleForm;
    
    // 只有在非全局规则并且所有字段都为空时才显示错误
    return !form.value.isGlobal && 
           form.get('goodsCode')?.value === '' && 
           form.get('goodsType')?.value === '' && 
           form.get('warehouseName')?.value === '';
  }
  
  /**
   * 全局规则切换事件
   */
  onGlobalChange(): void {
    if (this.ruleForm.value.isGlobal) {
      // 清空非全局规则的字段
      this.ruleForm.patchValue({
        goodsCode: '',
        goodsType: '',
        warehouseName: ''
      });
    }
  }

  ngOnDestroy(): void {
    // 取消订阅
    this.subscription.unsubscribe();
  }
} 